package com.anzuo.app.data.remote

import com.anzuo.app.BuildConfig
import com.anzuo.app.data.model.Item
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import java.util.concurrent.TimeUnit

/**
 * ApiService - 网络API服务接口
 * 使用Retrofit进行网络请求
 * 
 * @author AnZuo
 * @date 2024
 */
interface ApiService {

    /**
     * 获取数据列表
     */
    @GET("items")
    suspend fun getItems(): List<Item>

    companion object {
        /**
         * 创建ApiService实例
         */
        fun create(): ApiService {
            // 创建OkHttpClient，添加日志拦截器
            val okHttpClient = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .apply {
                    // 只在Debug模式下添加日志拦截器
                    if (BuildConfig.DEBUG) {
                        addInterceptor(
                            HttpLoggingInterceptor().apply {
                                level = HttpLoggingInterceptor.Level.BODY
                            }
                        )
                    }
                }
                .build()

            // 创建Retrofit实例
            val retrofit = Retrofit.Builder()
                .baseUrl(BuildConfig.API_BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
                .build()

            return retrofit.create(ApiService::class.java)
        }
    }
}

